/*
 * motor.c
 *
 * Created: 11/5/2013 7:13:57 PM
 *  Author: Tim
 */ 

#include "../src/Epiphany.h"

void pwmSetup();

void setPulseWidth(uint16_t width);

void setup()
{
	//put all your initializations here
	clockInit();
	pwmSetup();
	RTC_DelayInit();
}

void loop()
{

	//configure the for loop to power the motor from an effort of 0 to 100%
	for(;;)
	{
		
		//control the pulse width with the commented out line below
		
		//		setPulseWidth();

		//this is a delay used to slow down the process
		while(delayNotOver)
		{
			RTC_Delay_ms(1);
		}
	}
	
	//Part II add a second loop to slow the motor back down
	
	//Part III (optional) make the motor 
	//speed up 
	//slow down, 
	//change direction
	//repeat
	
	//HINT you will need to use more i/o pins to control the motor direction
	

}

void setPulseWidth(uint16_t width)
{
	//make sure we can't assign a value too high
	if(width > 1024) width = 1024;
	
	//send the width to the timer
	TCC0.CCB = width;
}

void pwmSetup()
{
	
	
	//Math stuff
	
	//cpu frequency is 32MHz
	
	//we want a timer that overflows at over 20KHz to prevent hearing the PWM through the DC motor (trust me you will appreciate it)
	
	//we want enough resolution to control the motor...10-bit ie 1024 cnts sounds good.
	
	//32,000,000/1024 = ~31kHz.  Sounds good no diviser needed
	
	//Configs

	//we will be using PWM on pin 0 of the DAQ, which is controlled by the xmega's PORTC1 pin.
	//this pin has pwm functionality through timer TCC0 according to the atxmeg32a4u datasheet.
	
	//make the daq pin 0 an output
	PORTC.DIRSET = 0x02;
	
	//setup timer C0 to have a divisor of 64 as we decided upon in the math section
	TCC0.CTRLA = TC_CLKSEL_DIV1_gc;
	
	//set the timer period to 1024
	
	TCC0.PER = 1024;
	
	//Enable timer control (PWM) of our selected i/o pin
	TCC0.CTRLB = TC0_CCBEN_bm;
	
}